package com.itheima.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Random;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.Enum.CementStatusEnum;
import com.itheima.Enum.CementTypeEnum;
import com.itheima.entity.*;
import com.itheima.mapper.*;
import com.itheima.pojo.po.AnnouncementPo;
import com.itheima.result.PageResult;
import com.itheima.service.IAccountAuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 用户认证Service业务层处理
 * 
 * @author guanhuaer
 * @date 2025-03-20
 */
@Service
public class AccountAuthenticationServiceImpl implements IAccountAuthenticationService
{
    @Autowired
    private AccountAuthenticationMapper accountAuthenticationMapper;
    @Autowired
    private AccountNotificationMapper notificationMapper;
    @Autowired
    private AccountMessageMapper messageMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private CertificationRulesMapper rulesMapper;
    @Autowired
    private CertificationInformationMapper informationMapper;


    /**
     * 查询用户认证
     * 
     * @param id 用户认证主键
     * @return 用户认证
     */
    @Override
    public AccountAuthentication selectAccountAuthenticationById(Long id)
    {
        return accountAuthenticationMapper.selectAccountAuthenticationById(id);
    }

    /**
     * 查询用户认证列表
     * 
     * @param accountAuthentication 用户认证
     * @return 用户认证
     */
    @Override
    public PageResult selectAccountAuthenticationList(AccountAuthentication accountAuthentication)
    {
        PageHelper.startPage(accountAuthentication.getPageNum(),accountAuthentication.getPageSize());
        Page<AccountAuthentication> page = accountAuthenticationMapper.selectAccountAuthenticationList(accountAuthentication);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 新增用户认证
     * 
     * @param accountAuthentication 用户认证
     * @return 结果
     */
    @Override
    public int insertAccountAuthentication(AccountAuthentication accountAuthentication)
    {   // 向用户消息表插入一条消息
        AccountMessage message = new AccountMessage();
        message.setUserId(accountAuthentication.getUserId());
        message.setTitle(LocalDate.now().toString() +"你提交了认证申请");
        message.setDescription("请等待管理员审核");
        message.setDatetime(new Date());
        message.setType(1L);
        message.setIsRead(0L);
        messageMapper.insertAccountMessage(message);
        // 用户认证
        AccountAuthentication auth = accountAuthenticationMapper.selectAccountAuthenticationByUserId(accountAuthentication.getUserId());
        if (accountAuthentication.getFileList()!=""){
            String substring = accountAuthentication.getFileList().substring(0, accountAuthentication.getFileList().length() - 1);
            accountAuthentication.setFileList(substring);
        }
        if (auth!= null){
            accountAuthentication.setId(auth.getId());
            accountAuthenticationMapper.updateAccountAuthentication(accountAuthentication);
        }else {
            accountAuthentication.setCreateDate(LocalDateTime.now());
            accountAuthenticationMapper.insertAccountAuthentication(accountAuthentication);
        }
        // 智能审核
        String result = smartAudit(accountAuthentication);
        if (result.equals("智能审核通过")){
            return 1;
        }
        // 向管理员发送通知
        // 查询管理员id
        List<Long> adminIds = accountAuthenticationMapper.selectAdminIds();
        message.setTitle("有新的 "+accountAuthentication.getUsername()+" 用户提交了认证申请");
        message.setDescription("请及时查看审核！");
        message.setType(2L);
        message.setStatus("info");
        message.setIsRead(0L);
        message.setExtra("待审核");
        for (Long id : adminIds) {
            message.setUserId(id);
            messageMapper.insertAccountMessage(message);
        }
        return 1;
    }
    /**
     * 智能审核
     * @param accountAuthentication
     * @return
     */
    @Override
    @Transactional
    public String smartAudit(AccountAuthentication accountAuthentication) {
        // 判断用户认证类型 根据类型查询审核规则
        CertificationRules rules1 = new CertificationRules();
        rules1.setUserType(accountAuthentication.getUserType());
        CertificationRules rules = rulesMapper.selectCertificationRulesList(rules1);
        // 判断认证资料是否为空
        if (accountAuthentication.getFileList()!=null && accountAuthentication.getFileList()!=""){
            if (rules.getFileList()==1){
                return "改用户需要人工审核认证资料";
            }
        }
        // 根据认证规则判断是否通过
        String sql="";
        // 1,认证用户名
        if (rules.getUsername()!=null){
            if (rules.getUsername()==0){
                sql+="and username= #{tion.username} ";
            }
            if (rules.getUsername()==1){
                sql+="and username like concat ('%',#{tion.username},'%') ";
            }
        }
        // 2,认证认证号
        if (rules.getWorkNumber()!=null){
            if (rules.getWorkNumber()==0){
                sql+="and work_number= #{tion.workNumber} ";
            }
            if (rules.getWorkNumber()==1){
                sql+="and work_number like concat ('%',#{tion.workNumber},'%') ";
            }
        }
        // 3,认证电话
        if (rules.getMobile()!=null){
            if (rules.getMobile()==0){
                sql+="and mobile= #{tion.mobile} ";
            }
            if (rules.getMobile()==1){
                sql+="and mobile like concat ('%',#{tion.mobile},'%') ";
            }
        }
        // 4,认证邮箱
        if (rules.getEmail()!=null){
            if (rules.getEmail()==0){
                sql+="and email= #{tion.email} ";
            }
            if (rules.getEmail()==1){
                sql+="and email like concat ('%',#{tion.email},'%') ";
            }
        }
        // 删除第一个and
        sql = sql.substring(3,sql.length());
        CertificationInformation information = informationMapper.selectInformationBySql(sql, accountAuthentication);
        if (information!=null){
            // 认证通过 更新用户信息
            SysUser user = new SysUser();
            user.setId(accountAuthentication.getUserId());
            user.setOccupation(accountAuthentication.getUserType());
            userMapper.update(user);
            // 向用户消息表插入一条消息
            AccountMessage message = new AccountMessage();
            message.setUserId(accountAuthentication.getUserId());
            message.setTitle("你提交的认证申请已通过");
            message.setDescription("你提交的"+(accountAuthentication.getUserType()==0?"学生":accountAuthentication.getUserType()==1?"教师":"管理员")
                    +"认证申请已通过"+"感谢您的认证");
            message.setDatetime(new Date());
            message.setType(1L);
            message.setIsRead(0L);
            messageMapper.insertAccountMessage(message);
            // 更新认证状态
            AccountAuthentication authentication = accountAuthenticationMapper.selectAccountAuthenticationByUserId(accountAuthentication.getUserId());
            authentication.setStatus(3);
            authentication.setUpdateDate(LocalDateTime.now());
            accountAuthenticationMapper.updateAccountAuthentication(authentication);
            return "智能审核通过";
        }
        return "智能审核不通过,请人工审核";
    }




    /**
     * 修改用户认证
     * 
     * @param accountAuthentication 用户认证
     * @return 结果
     */
    @Override
    @Transactional
    public int updateAccountAuthentication(AccountAuthentication accountAuthentication)
    {   // 向用户消息表插入一条消息
        AccountMessage message = new AccountMessage();
        message.setUserId(accountAuthentication.getUserId());
        //认证结果(0待认证，1通过，2不通过，3驳回)")
        String status = (accountAuthentication.getStatus()==1?"通过":
                accountAuthentication.getStatus()==2?"不通过":"驳回");
        message.setTitle("你提交的认证申请已"+status);
        message.setDescription(LocalDate.now().toString()+"管理员已审核 "+status);
        message.setDatetime(new Date());
        message.setType(1L);
        message.setIsRead(0L);
        messageMapper.insertAccountMessage(message);
        // 更改用户认证状态
        SysUser user = new SysUser();
        user.setId(accountAuthentication.getUserId());
        if (accountAuthentication.getStatus() == 1){
            user.setOccupation(accountAuthentication.getUserType());
            userMapper.update(user);
        }
        // 用户认证
        accountAuthentication.setUpdateDate(LocalDateTime.now());
        return accountAuthenticationMapper.updateAccountAuthentication(accountAuthentication);
    }

    /**
     * 批量删除用户认证
     * 
     * @param ids 需要删除的用户认证主键
     * @return 结果
     */
    @Override
    public int deleteAccountAuthenticationByIds(Long[] ids)
    {
        return accountAuthenticationMapper.deleteAccountAuthenticationByIds(ids);
    }

    /**
     * 删除用户认证信息
     * 
     * @param id 用户认证主键
     * @return 结果
     */
    @Override
    public int deleteAccountAuthenticationById(Long id)
    {
        return accountAuthenticationMapper.deleteAccountAuthenticationById(id);
    }

    /**
     * 根据用户id查询通知信息
     * @param userId
     * @return
     */
    @Override
    public AccountNotification selectAccountNotificationByUserId(Long userId) {
        return notificationMapper.selectAccountNotificationByUserId(userId);
    }

    /**
     * 更新通知状态
     * @param notification
     * @return
     */
    @Override
    public int updateAccountNotification(AccountNotification notification) {
        return notificationMapper.updateAccountNotification(notification);
    }

    /**
     * 根据用户id查询认证信息
     * @param userId
     * @return
     */
    @Override
    public AccountAuthentication selectAccountAuthenticationByUserId(Long userId) {
        return accountAuthenticationMapper.selectAccountAuthenticationByUserId(userId);
    }

    /**
     * 查询认证规则
     * @param userType
     * @return
     */
    @Override
    public CertificationRules selectCertificationRulesRule(Integer userType) {
        CertificationRules certificationRules = new CertificationRules();
        certificationRules.setUserType(userType);
        return rulesMapper.selectCertificationRulesList(certificationRules);
    }

    /**
     * 更新认证规则
     * @param rules
     * @return
     */
    @Override
    public int updateCertificationRulesRule(CertificationRules rules) {
        return rulesMapper.updateCertificationRules(rules);
    }


}
